package com.wnhz.work.jy.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.adapter.Home3Adapter;
import com.wnhz.work.jy.adapter.SearchAdapter;
import com.wnhz.work.jy.adapter.SearchLisrViewAdapter;
import com.wnhz.work.jy.bean.HomeFragment1.RecommendBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends BaseActivity implements View.OnClickListener, TextView.OnEditorActionListener, AdapterView.OnItemClickListener {
    private static final String TAG = "SearchActivity";
    private TextView title;
    private GridView gridView;
    private List<RecommendBean> beanList = new ArrayList<>();
    private SearchAdapter mAdapter;
    private EditText search_ed;
    private View history;
    private List<String> mlist = new ArrayList<>();
    private View ts;
    private SearchLisrViewAdapter adapter;
    private ListView listView;

    @ViewInject(R.id.include_occupied)
    private View include_occupied;
    @ViewInject(R.id.blank_img)
    private ImageView blank_img;
    @ViewInject(R.id.blank_tv)
    private TextView blank_tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        x.view().inject(this);
        findViewById(R.id.btn_main_left).setOnClickListener(this);

        SharedPreferences sp = getSharedPreferences("history.txt", Context.MODE_PRIVATE);
        if (!"".equals(sp) && sp != null) {
            for (int i = 0; i < 10; i++) {
                String con = sp.getString("name" + i, "");
                if (con != null && !"".equals(con)) {
                    mlist.add(con);
                }
            }
        }
        ts = findViewById(R.id.ts);
        gridView = (GridView) findViewById(R.id.gridView);
        search_ed = (EditText) findViewById(R.id.edit_search_input);
        history = findViewById(R.id.history);
        listView = (ListView) findViewById(R.id.listView);
        search_ed.setOnEditorActionListener(this);
        findViewById(R.id.view_search_text).setOnClickListener(this);
        findViewById(R.id.clean).setOnClickListener(this);
        mAdapter = new SearchAdapter(this,beanList);
        gridView.setAdapter(mAdapter);

//        mHandler.sendEmptyMessage(1);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchActivity.this, GoodDetailsMainActivity.class);
                intent.putExtra("goodId", beanList.get(position).getGoodId());
                startActivity(intent);
            }
        });

        adapter = new SearchLisrViewAdapter(this, mlist);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        tsshouorhide();
    }

    private void addDb(String content) {
        mlist.add(0, content);
        if (mlist.size() > 9) {
            mlist.remove(mlist.size() - 1);
        }

        for (int i = 0; i < mlist.size(); i++) {
            SharedPreferences sp = getSharedPreferences("history.txt", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("name"+i, mlist.get(i));
            editor.commit();

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.view_search_text:
                String search = search_ed.getText().toString();
                if (!"".equals(search)){

                    SharedPreferences sp = getSharedPreferences("history.txt", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    for (int i = 0; i < mlist.size(); i++) {
                        editor.putString("name" + i, mlist.get(i));
                    }
                    editor.commit();
                    addDb(search);
                    search(search);
                }
                break;
            case R.id.clean:
                mlist.clear();
                SharedPreferences sp = getSharedPreferences("history.txt", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                editor.commit();
                tsshouorhide();
                adapter.notifyDataSetChanged();
                break;
        }
    }

    private void tsshouorhide(){
        if (mlist.size() == 0){
            ts.setVisibility(View.VISIBLE);
        }else {
            ts.setVisibility(View.GONE);
        }
    }

    private void setBlank() {
        if (beanList.size() == 0) {
            blank_tv.setText("暂无搜索结果~");
            blank_img.setImageResource(R.mipmap.ic_sousuoweikong);
            include_occupied.setVisibility(View.VISIBLE);
        } else {
            include_occupied.setVisibility(View.GONE);
        }
    }

    private void search(String content){
        Map<String,Object> map = new HashMap<>();
        map.put("search",content);
        showDialog();
        XUtil.Post(ConfigUtil.SEARCH,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: "+result);
                try {
                    beanList.clear();
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    if ("1".equals(re)){
                        JSONArray array = json.optJSONArray("info");
                        if (array != null){
                            for (int i = 0; i < array.length(); i++) {
                                RecommendBean recommend = gson.fromJson(array.optString(i),RecommendBean.class);
                                beanList.add(recommend);
                            }
                        }
                        
                    }
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                if (history.getVisibility() == View.VISIBLE)
                    history.setVisibility(View.GONE);
                closeDialog();
                setBlank();
            }
        });
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH){
            // do something
            String search = search_ed.getText().toString();
            if (!"".equals(search)){

                addDb(search);
                search(search);
            }

        }
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        search(mlist.get(position));
    }
}
